import {
  mGetDevCheckDataNotPage,
  mGetDevCheckHistoryDataByParam,
  mSelectDevParam,
} from '@/api/device'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {FormInstance} from 'ant-design-vue'
import dayjs, {Dayjs} from 'dayjs'
import * as echarts from 'echarts'
import {ECharts} from 'echarts'
import {PropType} from 'vue'
//? 状态管理区 -----------------------------------
/**字典类型 状态数据 */
interface Device_xxx_List {
  /**所有检测参数 */
  device_param_list: SysDict.Item[]
}
interface Device_checkHistory_fixedParam_state extends Device_xxx_List {
  table: {
    dataSource: Device.CheckData[]
    pagination: Paging
    total: number
    pagination_handle: {
      change: Function
      showSizeChange: Function
    }
  }
  search: {
    devId: string | undefined
    startDate: Dayjs
    endDate: Dayjs
    paramName: string
  }
  checkDevInfo: {devId: number; devName: string} | null
  devParamList: Device.CheckParam[]
}
export let device_checkHistory_fixedParam_state =
  reactive<Device_checkHistory_fixedParam_state>({
    device_param_list: [],
    table: {
      dataSource: [],
      pagination: {
        page: 1,
        size: 20,
      },
      total: 0,
      pagination_handle: {
        change: ({page, size}: {page: number; size: number}) => {
          let {pagination} = toRefs(device_checkHistory_fixedParam_state.table)
          pagination.value.page = page
          pagination.value.size = size
          getTableDatas()
        },
        showSizeChange: ({page, size}: {page: number; size: number}) => {
          let {pagination} = toRefs(device_checkHistory_fixedParam_state.table)
          pagination.value.page = page
          pagination.value.size = size
          getTableDatas()
        },
      },
    },
    search: {
      devId: undefined,
      startDate: dayjs(),
      endDate: dayjs(),
      paramName: '',
    },
    checkDevInfo: null,
    devParamList: [],
  })
let echart: ECharts | null

//? 接口调用区 -----------------------------------
/**获取表格数据 */
export async function getTableDatas() {
  if (echart) echart.showLoading()

  let {
    dataSource,
    pagination,
    total: tableTotal,
  } = toRefs(device_checkHistory_fixedParam_state.table)
  let {search} = toRefs(device_checkHistory_fixedParam_state)
  let defaultData = {
    devId: search.value.devId,
    startDate: search.value.startDate?.format('YYYY-MM-DD 00:00:00') as string,
    endDate: search.value.endDate?.format('YYYY-MM-DD 23:59:59') as string,
    paramName: search.value.paramName,
  }

  if (defaultData.devId) {
    let res = await mGetDevCheckDataNotPage(defaultData).catch(err => {})
    if (!res) return
    dataSource.value = res.data
    // tableTotal.value = total
    // drawEchart()
  }
}

/**获取当前设备所有检测参数 */
export const getAllDevParams = async () => {
  let {checkDevInfo} = toRefs(device_checkHistory_fixedParam_state)
  if (checkDevInfo.value) {
    let res = await mSelectDevParam({devId: checkDevInfo.value.devId}).catch(
      err => {}
    )
    if (res && res.data.length > 0) {
      let {devParamList, search} = toRefs(device_checkHistory_fixedParam_state)
      devParamList.value = res.data
      search.value.paramName = res.data[0].paramName
      getTableDatas()
    }
  }
}

//? 组件事件区 -----------------------------------
/**获取路由传参传递过来的currentDevInfo */
export const handle_currentDevInfo_by_route_params_currentDevInfo =
  (currentDevInfo?: {devId: number; devName: string}) => {
    if (currentDevInfo) {
      let {checkDevInfo, search} = toRefs(device_checkHistory_fixedParam_state)
      let {page} = toRefs(device_checkHistory_fixedParam_state.table.pagination)

      if (checkDevInfo.value) {
        Object.assign(checkDevInfo.value, currentDevInfo)
      } else {
        checkDevInfo.value = currentDevInfo
      }

      search.value.devId = String(checkDevInfo.value.devId)

      page.value = 1
      console.log(search.value)
    }
  }
/**下拉选择输入关键字筛选 */
const filterOption = (input: string, option: any, target: string) => {
  return option[target].toLowerCase().indexOf(input.toLowerCase()) >= 0
}

//? 复用组件区 -----------------------------------

//? 页面组件区 -----------------------------------
export const FixedParamViewLeftNav = defineComponent({
  name: 'ViewLeftNav',
  setup() {
    let {router} = useGlobalAPI()

    const handle_back_btn_click = () => {
      let {checkDevInfo} = toRefs(device_checkHistory_fixedParam_state)
      router.push({
        path: '/device/list/checkHistory',
        query: {
          devId: checkDevInfo.value?.devId,
          devName: checkDevInfo.value?.devName,
        },
      })
    }
    return () => (
      <a-button class="w-full h-full text-base" onClick={handle_back_btn_click}>
        返回历史记录
      </a-button>
    )
  },
})

/**检测数据 固定参数 左侧搜索 */
export const CheckHistoryFixedParamViewLeft = defineComponent({
  name: 'ViewLeft',
  setup() {
    let {checkDevInfo} = toRefs(device_checkHistory_fixedParam_state)
    let {startDate, endDate} = toRefs(
      device_checkHistory_fixedParam_state.search
    )
    let {page} = toRefs(device_checkHistory_fixedParam_state.table.pagination)

    let {router} = useGlobalAPI()

    let formRef = ref<FormInstance>()

    let state_form = reactive<{
      dateRange: [Dayjs, Dayjs]
    }>({
      dateRange: [dayjs(), dayjs()],
    })
    watch(
      () => [startDate.value, endDate.value],
      n => {
        page.value = 1
      }
    )

    watch(
      () => state_form.dateRange,
      n => {
        console.log(n)
        startDate.value = n[0]
        endDate.value = n[1]
      }
    )

    /**提交表单且数据验证成功后回调事件 */
    const handle_viewLeftFilter_form_finish = async () => {
      getTableDatas()
    }

    /** 提交表单且数据验证失败后回调事件 */
    const handle_viewLeftFilter_form_finish_failed = () => {
      viewLeftFilter_returnEmit()
    }

    /**表单 重置按钮 点击 */
    const handle_viewLeftFilter_form_reset = () => {
      viewLeftFilter_returnEmit()
      nextTick(() => {
        getTableDatas()
      })
    }

    // 清空表单 关闭外层弹框
    const viewLeftFilter_returnEmit = () => {
      formRef.value?.resetFields()
    }

    return () => (
      <a-form
        class="h-full viewLeftFilter overflow-auto relative"
        v-model={[formRef, 'ref']}
        name="addSysdictType"
        model={state_form}
        label-col={{span: 8}}
        wrapper-col={{span: 16}}
        onFinish={handle_viewLeftFilter_form_finish}
        onFinishFailed={handle_viewLeftFilter_form_finish_failed}
      >
        <a-form-item label="设备名称" class="mx-2 my-4">
          {() => {
            if (checkDevInfo.value?.devName) {
              return (
                <div class="truncate">
                  <a-tooltip title={checkDevInfo.value?.devName}>
                    {checkDevInfo.value?.devName}
                  </a-tooltip>
                </div>
              )
            } else {
              return (
                <a-button
                  size="small"
                  type="primary"
                  onClick={() => {
                    router.push({name: 'device-list'})
                  }}
                >
                  前往设备列表
                </a-button>
              )
            }
          }}
        </a-form-item>
        <a-form-item
          name="dateRange"
          class="mx-2 my-4"
          label-col={{span: 0}}
          wrapper-col={{span: 24}}
        >
          <a-range-picker
            v-model={[state_form.dateRange, 'value']}
            format="YYYY/MM/DD"
          />
        </a-form-item>
        <div class="w-full h-mainViewfooter absolute left-0 bottom-0 m-0 px-4 border-t border-default flex justify-end items-center">
          <a-button type="primary" onClick={handle_viewLeftFilter_form_reset}>
            重置
          </a-button>
          <a-button class="ml-4 " type="primary" html-type="submit">
            查询
          </a-button>
        </div>
      </a-form>
    )
  },
})

/**检测数据 固定参数 表格 上方操作栏 */
export const CheckHistoryFixedParamMainViewNav = defineComponent({
  setup() {
    let {devParamList} = toRefs(device_checkHistory_fixedParam_state)
    let {paramName} = toRefs(device_checkHistory_fixedParam_state.search)

    const handle_devParam_click = (devParam: Device.CheckParam) => {
      paramName.value = devParam.paramName
      getTableDatas()
    }
    return () => (
      <div class="w-full h-mainViewNav bg-white px-4">
        <ul class="h-full flex justify-between items-center overflow-x-auto">
          {devParamList.value.map((devParam, idx) => {
            return (
              <li
                class={[
                  'h-full flex-1 text-center flex justify-around items-center',
                ]}
              >
                <a-button
                  class={[
                    'min-w-20  px-2 text-base truncate rounded',
                    paramName.value === devParam.paramName
                      ? 'border-primary bg-primary text-white'
                      : '',
                  ]}
                  onClick={() => handle_devParam_click(devParam)}
                >
                  {devParam.paramName}
                </a-button>
                <span
                  class={[
                    'border-r border-default h-1/3',
                    idx === devParamList.value.length - 1 ? 'hidden' : '',
                  ]}
                ></span>
              </li>
            )
          })}
        </ul>
      </div>
    )
  },
})

/**检测数据 固定参数 表格 上方图表展示栏 */
export const CheckHistoryFixedParamMainViewEchart = defineComponent({
  setup() {
    let {dataSource} = toRefs(device_checkHistory_fixedParam_state.table)

    watch(
      () => dataSource.value,
      n => {
        if (n.length) {
          nextTick(() => {
            drawEchart()
          })
        }
      }
    )

    onMounted(() => {
      if (echart) {
        echart.dispose()
        echart = null
      }
    })

    function drawEchart() {
      if (!echart) {
        echart = echarts.init(
          document.getElementById('echartByParam') as HTMLElement
        )
      } else {
        console.log('清除了echarts')
        echart.clear()
      }

      let {paramName} = toRefs(device_checkHistory_fixedParam_state.search)

      let xAxisData = dataSource.value.map(item => item.checkTime)
      let xAxisDataMap = xAxisData.map(item => new Date(item || '').getTime())
      let xAxisDataMapFilter = xAxisDataMap
        .map((item, idx) => {
          if (idx > 0) {
            let abs5 = item - 300000 - xAxisDataMap[idx - 1]
            let abs10 = item - 600000 - xAxisDataMap[idx - 1]
            if (Math.abs(abs5) < 295000) {
              if (Math.abs(abs5) > 5000)
                return {
                  idx,
                  item: [xAxisData[idx - 1], xAxisData[idx]],
                }
            } else if (Math.abs(abs10) < 595000) {
              if (Math.abs(abs10) > 5000)
                return {
                  idx,
                  item: [xAxisData[idx - 1], xAxisData[idx]],
                }
            }
          }
          return false
        })
        .filter(item => item)
      console.log(xAxisDataMapFilter)
      let seriesLineData = dataSource.value.map(item => item.checkDataValue)
      let seriesName = paramName.value

      let option = {
        grid: {
          left: '4%',
          right: '4%',
          bottom: '10%',
          top: '8%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData,
        },
        yAxis: {
          type: 'value',
          // minInterval: 0.01, //坐标轴刻度最小间隔
        },
        tooltip: {
          trigger: 'axis',
        },
        dataZoom: [
          {
            type: 'inside',
            start: 90,
            end: 100,
          },
          {
            start: 90,
            end: 100,
          },
        ],
        series: [
          {
            type: 'line',
            name: seriesName,
            showSymbol: false,
            zlevel: 1,
            z: 1,
            lineStyle: {
              width: 0,
            },
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgb(1, 191, 236)',
                },
                {
                  offset: 1,
                  color: 'rgb(128, 255, 165)',
                },
              ]),
            },
            data: seriesLineData,
          },
        ],
      }

      echart && echart.setOption(option)
      console.log('渲染了echarts', echart)
      echart.hideLoading()
    }
    return () => (
      <div class="h-full border-b border-default">
        <div id="echartByParam" class="w-full h-full"></div>
      </div>
    )
  },
})

/**检测数据 固定参数 表格 */
export const CheckHistoryFixedParamTable = defineComponent({
  setup(props) {
    let {dataSource} = toRefs(device_checkHistory_fixedParam_state.table)
    let {page, size} = toRefs(
      device_checkHistory_fixedParam_state.table.pagination
    )

    type Key = string | number
    /**表格头 */
    let columns: CColumn<Device.CheckData>[] = [
      {
        title: '序号',

        isIndex: true,
        ellipsis: true,
        width: 80,
        dataIndex: 'index',
      },
      {
        title: '检测参数',
        dataIndex: 'checkDataName',
        ellipsis: true,
      },
      {
        title: '检测值',
        dataIndex: 'checkDataValue',
        ellipsis: true,
      },
      {
        title: '检测时间',
        dataIndex: 'checkTime',
        ellipsis: true,
      },
      {
        title: '操作',
        dataIndex: 'utils',
        isUtil: true,
        width: 140,
      },
    ]

    /**处理表格头伸缩 */
    function handleResizeColumn(w: any, col: any) {
      col.width = w
    }
    const state = reactive<{
      selectedRowKeys: Key[]
      loading: boolean
    }>({
      selectedRowKeys: [], // Check here to configure the default column
      loading: false,
    })

    const onSelectChange = (selectedRowKeys: Key[], selectedRows: any) => {
      state.selectedRowKeys = selectedRowKeys
    }
    return () => (
      <div class="h-2/3">
        <a-table
          dataSource={dataSource.value}
          columns={columns}
          rowKey={'checkDataId'}
          pagination={false}
          onResizeColumn={handleResizeColumn}
          scroll={{
            scrollToFirstRowOnChange: true,
            y: 438,
          }}
          row-selection={{
            selectedRowKeys: state.selectedRowKeys,
            onChange: onSelectChange,
          }}
        >
          {{
            bodyCell: ({
              text,
              record,
              index,
              column,
            }: {
              text: string
              record: Device.CheckData
              index: number
              column: CColumn<Device.CheckData>
            }) => {
              if (column.isUtil) {
                return (
                  <CheckHistoryFixedParamHandleBtn
                    record={record}
                  ></CheckHistoryFixedParamHandleBtn>
                )
              } else if (column.isIndex) {
                return (
                  <div class="truncate">
                    {(page.value - 1) * size.value + index + 1}
                  </div>
                )
              } else {
                switch (column.dataIndex) {
                  default:
                    return <div class="truncate">{text}</div>
                }
              }
            },
          }}
        </a-table>
      </div>
    )
  },
})

/**检测数据 固定参数 表格 操作栏 */
export const CheckHistoryFixedParamHandleBtn = defineComponent({
  props: {
    record: {
      type: Object as PropType<Device.CheckData>,
      default: {},
    },
  },
  setup(props) {
    // let {visible, title, type} = toRefs(device_checkHistory_fixedParam_state.modal)
    // let {edit_source} = toRefs(device_list_state.form)

    const handle_type_edit_btn_click = () => {
      console.log(props.record)
      // visible.value = true
      // type.value = 'editType'
      // title.value =
      //     '修改参数: ' +
      //     props.record.devTypeCode +
      //     '——' +
      //     props.record.devTypeDataCode

      // //给修改表单数据源赋值
      // edit_source.value.devTypeDataDesc =
      //     props.record.devTypeDataDesc || ''
      // edit_source.value.devTypeDataId = props.record.devTypeDataId
      // edit_source.value.devTypeDataValue =
      //     props.record.devTypeDataValue || ''
    }

    return () => (
      <div class="">
        <span
          class="mr-2 text-primary border-b cursor-pointer"
          onClick={handle_type_edit_btn_click}
        >
          编辑
        </span>
      </div>
    )
  },
})

/**检测数据 固定参数 分页 */
export const CheckHistoryFixedParamPagination = defineComponent({
  emits: ['change', 'showSizeChange'],
  setup(props, {emit}) {
    let {size, page} = toRefs(
      device_checkHistory_fixedParam_state.table.pagination
    )
    let {total} = toRefs(device_checkHistory_fixedParam_state.table)
    /**表格分页配置 */
    let pagination = reactive({
      current: page, //当前页数
      pageSize: size,
      defaultPageSize: size, //默认的每页条数
      pageSizeOptions: [10, 20, 30, 50, 100], //指定每页可以显示多少条
      total: total, //数据总数
      hideOnSinglePage: false, //只有一页时是否隐藏分页器
      showQuickJumper: true, //是否可以快速跳转至某页
      showSizeChanger: true, //是否可以改变 pageSize
      showTotal: (total: number, range: number[]) => {
        return '共有' + total + '条'
      }, //用于显示数据总量和当前数据顺序
      size: 'small',
      onChange: (page: number, pageSize: number) => {
        device_checkHistory_fixedParam_state.table.pagination_handle.change({
          page,
          size: pageSize,
        })
      },
      onShowSizeChange: (current: number, size: number) => {
        device_checkHistory_fixedParam_state.table.pagination_handle.showSizeChange(
          {
            page: current,
            size,
          }
        )
      },
    })
    return () => (
      <a-pagination
        current={pagination.current}
        page-size={pagination.pageSize}
        total={pagination.total}
        defaultPageSize={pagination.defaultPageSize}
        pageSizeOptions={pagination.pageSizeOptions}
        hideOnSinglePage={pagination.hideOnSinglePage}
        showQuickJumper={pagination.showQuickJumper}
        showSizeChanger={pagination.showSizeChanger}
        showTotal={pagination.showTotal}
        size={pagination.size}
        onChange={pagination.onChange}
        onShowSizeChange={pagination.onShowSizeChange}
      ></a-pagination>
    )
  },
})
